/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ipfms.manager;

import com.google.inject.Inject;
import com.wideplay.warp.persist.Transactional;
import ipfms.dao.BuildingDAO;
import ipfms.dao.BuildingImgDAO;
import ipfms.model.Building;
import ipfms.model.BuildingImg;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author fikri
 */
public class BuildingManager {
    
    @Inject
    protected com.google.inject.Provider<Session> sessionProvider;
    
    @Inject BuildingDAO buildingDAO;
    
    @Inject BuildingImgDAO buildingImgDAO;
    
    public List<Building> searchByStateType(Building building){
        
        StringBuilder sb = new StringBuilder();
        sb.append("select b from Building b where publish = :publish");
        if (building.getBuildingState() != null) sb.append(" and b.buildingState = :state");
        if (StringUtils.isNotBlank(building.getBuildingName())) sb.append(" and b.buildingName like :name");
        if (building.getBuildingType() != null) sb.append(" and b.buildingType.code = :type");        
        
        Session session = sessionProvider.get();
        Query query = session.createQuery( sb.toString() );
        query.setParameter("publish", 'Y');
        if (building.getBuildingState() != null)  query.setString("state", building.getBuildingState().getCode());
        if (StringUtils.isNotBlank(building.getBuildingName()))  query.setString("name", "%" + building.getBuildingName() + "%");
        if (building.getBuildingType() != null)  query.setString("type", building.getBuildingType().getCode());

        return query.list();        
    }   
    
    @Transactional
    public void saveOrUpdate( Building building ) {
        buildingDAO.saveOrUpdate(building);
    }
    
    @Transactional
    public void saveOrUpdateImg ( BuildingImg buildingImg ) {
        buildingImgDAO.saveOrUpdate(buildingImg);
    }
    
    public Building findById (  Integer id ) {
        return buildingDAO.findById(id);
    }
    
    
    
}
